<script setup lang='ts'>
import { useGetStatsList, useStatsAdd, useStatsDel } from '@fl/api/man-api/pricing-tool'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'
import { computed, nextTick, ref } from 'vue'

const props = withDefaults(defineProps<{
    data?: any
    limit?: number
}>(), {
    limit: 50,
})

const emits = defineEmits(['cancel'])
const { data, limit } = toRefs(props)
const { createMessage } = useMessage()

const tableData = ref<any>([])
const tableRef = ref()

const cache = ref<any>([])

// 查询已有属性
const params = computed(() => ({ categoryId: data.value ?? '' }))
const { data: list, isLoading, refetch } = useGetStatsList(params)
watchEffect(() => {
    if (list.value) {
        tableData.value = cloneDeep(list.value)
        cache.value = cloneDeep(list.value)
    }
})

const { mutate: mutateDel } = useStatsDel()
function doDel({ $index, row }) {
    ElMessageBox.confirm('该操作将永久删除，是否继续?', '提示', { type: 'warning' })
        .then(() => {
            if (row?.id) {
                mutateDel(row.id, {
                    onSuccess: () => {
                        ElMessage({ message: '操作成功', type: 'success' })
                    },
                })
            }
            else {
                ElMessage({ message: '操作成功', type: 'success' })
            }

            tableData.value.splice($index, 1)
        })
}

function doAdd() {
    const len = tableData.value.length
    if (len >= limit.value) {
        ElMessage.error(`最多添加${limit.value}条数据！`)
        return
    }

    let isNext = true
    const target = tableData.value[len - 1]

    // 校验上条数据 是否填写完整
    if (len && /^\s*$/.test(target.specName)) {
        isNext = false
    }

    if (!isNext) {
        ElMessage.error(`请填写完整第${len}条数据`)
        return
    }

    const models = tableData.value.map((v: any) => v.specName)
    const arr = models.slice(0, models.length - 1)

    if (len > 1 && arr.includes(target.specName)) {
        ElMessage.error(`第${len}条属性名称已存在`)
        return
    }

    tableData.value.push({
        categoryId: Number(data.value),
        specName: '',
    })

    if (tableData.value.length > 5) {
        nextTick(() => {
            tableRef.value.setScrollTop(len * 300)
        })
    }
}

// 目录新增 编辑保存
const { mutate } = useStatsAdd()
function doSave() {
    const target = tableData.value
    if (!tableData.value.length) {
        createMessage.error('请添加属性')
        return
    }

    // 重复校验
    const noRepeat = new Set([...target.map((v: any) => v.specName)])
    if (target.length !== noRepeat.size) {
        ElMessage.error(`存在重复属性名称`)
        return
    }

    const isEnpty = target.some((v: any) => !v.specName || v.specName.includes(' '))
    if (isEnpty) {
        ElMessage.error(`请填写完整再保存`)
        return
    }

    mutate(tableData.value, {
        onSuccess: () => {
            createMessage.success('操作成功')
            refetch()
        },
    })
}

function doCancel() {
    emits('cancel')
}

function doBlur({ row }) {
    if (row.specName === '') {
        ElMessage.error(`请输入变量名`)
        return
    }

    if (row.specName.includes(' ')) {
        ElMessage.error(`请输入非空字符`)
    }
}

// 检测是否存在未保存数据
function hasDraft() {
    return cache.value.length !== tableData.value.length || JSON.stringify(cache.value) !== JSON.stringify(tableData.value)
}

defineExpose({
    hasDraft,
})
</script>

<template>
    <div class="mb-20 c-#1d2129 font-600">
        属性列表
    </div>

    <el-table ref="tableRef"
              v-loading="isLoading"
              :data="tableData"
              stripe
              style="width: 100%"
              height="300"
    >
        <el-table-column label="序号"
                         type="index"
                         width="55"
        />

        <el-table-column label="属性名称">
            <template #header>
                <span><span class="mr-5 c-red">*</span>属性名称</span>
            </template>

            <template #default="scope">
                <el-input v-model="scope.row.specName"
                          maxlength="20"
                          type="text"
                          show-word-limit
                          style="max-width: 300px;"
                          placeholder="请输入"
                          clearable
                          @blur="doBlur(scope)"
                />
            </template>
        </el-table-column>

        <el-table-column label="操作"
                         width="90"
        >
            <template #default="scope">
                <el-button link
                           type="danger"
                           @click="doDel(scope)"
                >
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-button class="mt-20"
               type="primary"
               plain
               @click="doAdd"
    >
        + 添加属性
    </el-button>

    <div class="mt-20 text-center w-full">
        <el-button type="primary"
                   @click="doSave"
        >
            保存
        </el-button>

        <el-button @click="doCancel">
            取消
        </el-button>
    </div>
</template>

<style lang="scss" scoped></style>
